package com.radiation.rms.controller;

import com.alibaba.fastjson.JSON;
import com.radiation.rms.common.RMSConstant;
import com.radiation.rms.common.RMSDictionary;
import com.radiation.rms.entity.AbnormalData;
import com.radiation.rms.entity.RealTimeData;
import com.radiation.rms.service.AbnormalDataService;
import com.radiation.rms.service.RealTimeDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RadiationController {
    @Autowired
    private RealTimeDataService realTimeDataService;

    @Autowired
    private AbnormalDataService abnormalDataService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${socket.port}")
    private Integer socketPort;

    public void initialize() {
        // 客户端
        // 1、创建客户端Socket，指定服务器地址和端口
        // 定义一个接收端，并且指定了接收的端口号
        DatagramSocket socket = null;
        try {
            log.info("制定端口号：{}", socketPort);
            socket = new DatagramSocket(socketPort);
        } catch (SocketException e) {
            e.printStackTrace();
        }

        while (true) {
            byte[] buf = new byte[1024];
            // 解析数据包
            DatagramPacket packet = new DatagramPacket(buf, buf.length);
            try {
                socket.receive(packet);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String ip = packet.getAddress().getHostAddress();
            byte[] arr = packet.getData();
            String data = null;
            //data = new String(arr, 0, packet.getLength());
            log.error("收到 " + ip + " 发来的消息：" + bytesToHexString(buf));
            String ret = bytesToHexString(buf);
            //  String ret = "47 38 30 31 33 35 36 32 fe 0d ff 06 6e ff 53 51 55 65 78 67 19 21 14 c7 cb fe 0c 01 07 e2 09 06 10 01 04 01 2f 01 0a 27 10 00 3c 1c 59 15 1d";
            String actual = ret.substring(4, 6);
            if (!actual.equals("03")) {
                return;
            }
            System.out.println("---");
            String substring = ret.substring(0, 4);
            int mac = Integer.parseInt(substring, 16);
            String ret1 = ret.substring(8, 16);
            //010304 14000000ffc3
            log.info("record原始值" + ret1);
            String reverse = reverse(ret1);
            //截取14000000  0014  转换成十进制 20 再除以100 0.2就是得到的最终的辐射计量值  正常数值2.5
            //14140000 1414  转换成十进制 5140 再除以100 51.4就是得到的最终的辐射计量值
            int i = Integer.parseInt(reverse, 16);
            double record = i / 100.00;
            System.out.println(record);
            redisTemplate.opsForValue().set(RMSDictionary.deviceEnum.DEVICE_PREFIX.getCode() + mac, record + "", 10 * 60 * 1000, TimeUnit.MILLISECONDS);
            RealTimeData realTimeData = new RealTimeData();
            realTimeData.setRecord(record);
            realTimeData.setMac(mac + "");
            realTimeData.setGmtCreate(new Date());
            realTimeData.setGmtModified(new Date());
            realTimeData.setIsDeleted(false);
            realTimeData.setStatus(RMSConstant.NORMAL);

            if (record > 2.5) {
                AbnormalData abnormalData = new AbnormalData();
                abnormalData.setRecord(record);
                abnormalData.setMac(mac + "");
                abnormalDataService.save(abnormalData);
                realTimeData.setStatus(RMSConstant.ABNORMAL);
            }
            realTimeDataService.save(realTimeData);
            BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps("device:info");
            hashOps.put(mac + "", JSON.toJSONString(realTimeData));
            log.info("成功");
        }
    }


    /**
     * byte数组转换成十六进制(bytesToHexString)
     *
     * @param src
     * @return
     */
    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }

        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    private static String reverse(String source) {
        int z = source.length() / 2;
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < source.length(); i += 2) {
            String substring = source.substring(i, i + 2);
            stringBuilder.insert(0, substring);
        }
        return stringBuilder.toString();
    }

    public static void main(String[] args) {
        String aa = "14000000";
        System.out.println(reverse(aa));
        String reverse = reverse(aa);
        String s = bytesToHexString(reverse.getBytes());

        int i = Integer.parseInt(reverse, 16);
        double record = i / 100.00;
        System.out.println(record);
    }
}
